package UIFree.controls.imageItems
{
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	import UIFree.uif_loader;
	
	import UIUtils.uif_util;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class uif_squarePreview extends uif_ecomponent {
		private var _loader: uif_loader;
		private var _bitmap: Bitmap;
		public function uif_squarePreview(parent:uif_component, ax:int=0, ay:int=0, asize:int=0, styleClass:Object='') {
			super(parent, ax, ay, asize, asize, styleClass);
			createComponents();
		}
		
		protected function createComponents(): void {
			var inner: Rectangle = getInner();
			_bitmap = new Bitmap(new BitmapData(inner.width, inner.height));
			_bitmap.x = inner.x;
			_bitmap.y = inner.y;
			addChild(_bitmap);
		}
		
		public function load(url: String): void {
			_loader = new uif_loader(null, url, doComplete);
		}
		
		protected function get bitmap(): Bitmap {
			return _bitmap;
		}
		
		protected function get loader(): uif_loader {
			return _loader;
		}
		
		protected function doComplete(e: Event): void {
			refreshBitmap();
		}
		
		protected function refreshBitmap(): void {
			_bitmap.bitmapData.draw(_loader, getMatrix());
		}
		
		protected function getMatrix(): Matrix {
			var inner: Rectangle = getInner();
			var rect: Rectangle = uif_util.EnterHere(inner, _loader.size, false);
			var scale: Number = rect.width/_loader.size.x;
			return new Matrix(scale, 0, 0, scale, rect.x - inner.x, rect.y - inner.y);
		}
		
		override public function dispose():void {
			if (_loader) _loader.unload();
			_bitmap.bitmapData.dispose();
			removeChild(_bitmap);
			super.dispose();
		}
	}
}